<template>
  <div class="container">
    <header-bg></header-bg>
    <!-- 用户信息 -->
    <div class="head-box mar-b-10" ref="address" @click="chooseAddress">
      <div class="flex flex-between head-content">
        <div>
          <div v-if="!addressNameStr" class="flex v-align-c">
            <img
              v-if="fileSpace"
              class="width-12 height-12 mar-r-6"
              :src="fileSpace + '/images/icon-corss-add-2.png'" alt="">
            <span class="font-18 font-w">新建收货地址</span>
          </div>
          <div class="font-18 font-w font-color memberinfo">
            <span class="label-ad-sp mar-t-7">
              <span
                v-if="memberInfo.addressLabel"
                class="font-11 width-30 height-15 flex flex-center mar-r-10 font-normal"
                :class="'label-'+ memberInfo['labelStyle']">
                <span>{{memberInfo.addressLabel}}</span>
              </span>
            </span>
            <span>{{addressNameStr}}{{memberInfo.communityName}}{{memberInfo.houseNum}}</span>
          </div>
          <div v-if="addressNameStr" class="font-15 mar-t-3 memberinfo">
            <span>{{memberInfo.receiverName}}</span>
            <span class="mar-l-6">{{memberInfo.receiverPhone}}</span>
          </div>
        </div>
        <div>
          <icon
            class="iconfont icon-arrow-right icon-next-a mar-t-1 mar-r--1 font-16"></icon>
        </div>
      </div>
    </div>
    <!-- 商品列表 -->
    <div class="bg-color-white border-radius-5 mar-b-10">
      <div class="order-list-box"  v-for="(item, index) in listData" :key="index">
        <div class="flex">
          <div class="order-img">
            <img :src="item.goodsImage" alt="" v-if="item.goodsImage" class="width-90 height-90">
          </div>
          <div class="flex-col order-text-info mar-l-10">
            <div>
              <p class="font-16 font-color-2 line-1 font-w">{{item.goodsTitle}}</p>
              <div v-if="item.skuDetail" class="flex flex-between v-align-c mar-t-5">
                <span class="font-11 font-color-9 norm">{{item.skuDetail}}</span>
                <span class="font-15 font-w font-color-3 flex-item align-r sku-r-num">x{{item.goodsNum}}</span>
              </div>
            </div>
            <div v-if="item.deliverySupportFlag === 1" class="flex v-align-c flex-between mar-b--1">
              <span class="font-12 font-red" v-if="item.specimenPrice === 0">免费寄样</span>
              <span v-else class="font-16 font-w"><span class="font-12">￥</span>{{item.specimenPrice}}</span>
              <span v-if="!item.skuDetail" class="font-15 font-w font-color-3">x{{item.goodsNum}}</span>
            </div>
            <div v-else class="hint-box">
              <span>当前收货地址不支持配送该商品</span><span @click="deleteGoods(item)">×</span>
            </div>
          </div>
        </div>
        <div v-if="getRoleType === 2" class="flex v-align-b font-12 ratio-bar mar-t-10 pad-t-7 pad-b-5">
          <div class="flex-item pad-l-25">
            <div>{{ item.sampleGoodsTotalRatio }}%</div>
            <div class="font-color-9 font-11 mar-t--4">应获佣金</div>
          </div>
          <div class="flex-item pad-l-14">
            <div>{{ item.myRatio}}%</div>
            <div class="font-color-9 font-11 mar-t--4">实获佣金</div>
          </div>
          <div class="mar-r-17">
            <div class="flex v-align-c anchor-ratio-field">
              <van-field
                placeholder="请输入"
                :value="item.sampleAnchorRatio"
                type="digit"
                @change="ratioChange($event, item)"/>
              <div class="per-tag font-color-9 pad-l-4 pad-r-3">%</div>
            </div>
            <div class="font-color-9 font-11 pad-l-9">主播佣金</div>
          </div>
        </div>
        <div v-if="getRoleType === 2" class="comment-bar mar-t-8 pad-3">
          <van-field
            label="商品备注："
            :value="item.sellerWords"
            @change="sellerWordsChange($event, item)"
            maxlength="50"
            placeholder="50个字以内(选填)"
            :border="false"/>
        </div>
      </div>
    </div>
    <!-- 主播留言 -->
    <div class="mar-b-10">
      <div class="remark-box box-layout">
        <span>主播留言</span><input v-model="comment" class="mar-l-25 flex-item" maxlength="50" placeholder="50字以内  (选填)"/>
      </div>
    </div>
    <!-- 商品小计 运费 -->
    <div class="mar-b-30">
      <div class="flex-col pad-16 bg-color-white goods-other-info">
        <div class="flex flex-between font-color-3">
          <span class="font-15">商品小计</span>
          <span class="font-10">￥<span class="font-12">{{ resData.goodsPriceTotal }}</span></span>
        </div>
        <div class="flex flex-between font-color-3 mar-t-16">
          <span class="font-15">运费</span>
          <span class="font-10"><span class="font-12">{{ freight === '0.00' ? '免运费' : '¥' + freight }}</span></span>
        </div>
      </div>
    </div>
    <div class="height-50"></div>
    <!-- 底部 按钮 -->
    <div class="btn-position">
      <div class="bottom-area-box" :style="{background: notSupportNum? '#D5D5D5' : '#3C3834'}">
        <div class="flex-col">
          <span class="font-11" :class="notSupportNum? 'font-color-9': 'font-white'">￥<span class="font-13">{{total}}</span></span>
          <span class="font-12 font-color-9">共{{resData.goodsNum}}件</span>
        </div>
        <div class="sure-btn flex flex-center font-16" :class="notSupportNum ? 'dis-active': 'active'" @click="submitPay">
          确认下单
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import headerBg from '@/components/headerBg'
import { doGetOrderCheck, submitOrder } from '@/api/shop'
import { getAddress } from '@/api/address'
import { listEnterpriseMessageConfig } from '@/api/common'
export default {
  data() {
    return {
      address: '',
      addressNameStr: '',
      memberInfo: {
        addressId: '',
        receiverName: '',
        receiverPhone: '',
        addressName: '',
        address: ''
      },
      comment: '', // 主播留言
      goodsType: '',
      isCart: false,
      cartIds: [],
      notSupportNum: 0, // 计算不支持配送的商品件数
      listData: [],
      memberStore: {}, // 店铺信息
      freight: 0,
      totalPrice: 0,
      resData: {},
      messageIds: [],
      submitStatus: false,
      shareMemberId: null,
      goodsListData: []
    }
  },
  components: {headerBg},
  computed: {
    total() {
      let total = 0
      this.listData.forEach((item, index) => {
        total = item.deliverySupportFlag === 1 ? (total * 1 + item.specimenPrice * item.goodsNum).toFixed(2) : total * 1 + 0
      })
      total = isNaN((total * 1 + this.resData.postFee * 1).toFixed(2)) ? '0.00' : (total * 1 + this.resData.postFee * 1).toFixed(2)
      this.totalPrice = total
      return total
    }
  },
  onLoad() {
    // 初始化data
    Object.assign(this.$data, this.$options.data())
  },
  onShow() {
    this.goodsListData = JSON.parse(this.getCurrentPage().query.goodsList)
    // this.goodsListData = [
    //   {
    //     cartId: '1466289494465642497',
    //     goodsId: '1430368707481403393',
    //     goodsNum: 1,
    //     skuId: '1430368707527540743'
    //   },
    //   {
    //     cartId: '1466287665078009858',
    //     goodsId: '1431142558284869634',
    //     goodsNum: 1,
    //     skuId: ''
    //   }
    // ]
    // console.log('goodsListData 111', this.goodsListData)
    this.shareMemberId = this.getCurrentPage().query.shareMemberId || this.$store.state.shareMemberId
    if (this.$pt.getStorageSync('addressId')) {
      this.addressTips = false
      this.addressGetEls(this.$pt.getStorageSync('addressId'))
    }
  },
  mounted() {
    this.$pt.showLoading({
      title: '加载中',
      mask: true
    })
    this.$pt.removeStorageSync('pageBuyFrom')
    this.initMemberInfo()
    this.messageConfig()
    setTimeout(() => {
      this.$pt.hideLoading()
    }, 1000)
  },
  onHide() {
    this.$pt.removeStorageSync('addressId')
  },
  onUnload() {
    this.$pt.removeStorageSync('addressId')
  },
  methods: {
    messageConfig() {
      this.messageIds = []
      const dataArr = ['3101', '3103']
      let dataStr = dataArr.toString()
      listEnterpriseMessageConfig({
        memberId: this.getMemberId,
        ascriptionTypes: dataStr
      }).then((response) => {
        if (response.isError) return
        response.data.forEach(item => {
          if (item.miniMadeId) {
            this.messageIds.push(item.miniMadeId)
          }
        })
      }).catch(() => {
      })
    },
    // 获取地址信息
    addressGetEls(addressId) {
      getAddress(addressId).then((response) => {
        if (response.isError) return
        this.memberInfo.addressId = addressId
        this.$pt.removeStorageSync('addressId')
        // this.memberInfo.receiverName = response.data.receiverName
        // this.memberInfo.receiverPhone = response.data.receiverPhone
        // this.address = response.data.addressName + ' ' + response.data.address
        this.initMemberInfo()
      }).catch(() => {
      })
    },
    // 选择地址
    chooseAddress() {
      this.$pt.setStorageSync('pageBuyFrom', true)
      this.$pt.navigateTo({url: '/pages/personal/address/main'})
    },
    // 删除收货不支持配送的 货品
    deleteGoods(goods) {
      // this.goodsListData
      let index = this.goodsListData.findIndex(listItem => {
        return listItem.cartId === goods.cartId
      })
      if (index > -1) {
        this.goodsListData.splice(index, 1)
      }
      if (this.goodsListData.length) {
        this.initMemberInfo()
      } else {
        this.$pt.navigateBack({detail: -1})
      }
      this.radio = ''
    },
    initMemberInfo() {
      let params = {
        memberId: this.getMemberId,
        customerId: this.getCustomerId,
        addressId: this.memberInfo.addressId || this.$pt.getStorageSync('addressId'),
        roleType: this.getRoleType ? this.getRoleType : '',
        orderCheckGoodsList: this.goodsListData
      }
      return doGetOrderCheck(params).then((response) => {
        if (response.isError) {
          this.notSupportNum = 1
          return
        }
        // console.log('核对订单信息', response.data)
        this.resData = response.data
        if (this.isCart) {
          this.listData = response.data.goodsList
          // 获取有几款商品不支持配送
          let temp = response.data.goodsList.filter(item => {
            return item['deliverySupportFlag'] === 0
          })
          this.notSupportNum = temp.length
        } else {
          this.listData = response.data.cartList
          // 获取有几款商品不支持配送
          let temp = response.data.cartList.filter(item => {
            return item['deliverySupportFlag'] === 0
          })
          this.notSupportNum = temp.length
        }
        this.listData.forEach(item => {
          // item.sampleGoodsTotalRatio = 10
          if (!item.sampleGoodsTotalRatio) {
            item.sampleGoodsTotalRatio = '0.00'
            this.$set(item, 'sampleGoodsTotalRatio', '0.00')
          }
          item.myRatio = item.sampleGoodsTotalRatio
          this.$set(item, 'myRatio', item.sampleGoodsTotalRatio)
          item.sampleAnchorRatio = ''
          this.$set(item, 'sampleAnchorRatio', '')
          item.sellerWords = ''
          this.$set(item, 'sellerWords', '')
        })
        if (response.data.address) {
          this.memberInfo = response.data.address
          if ('addressLabel' in this.memberInfo) {
            let label = ''
            switch (this.memberInfo.addressLabel) {
              case '公司':
                label = 1
                break
              case '家':
                label = 2
                break
              case '其他':
                label = 3
                break
              case '学校':
                label = 4
                break
            }
            this.memberInfo.labelStyle = label
          }
        }
        if ('addressName' in this.memberInfo) {
          this.addressNameStr = this.memberInfo.addressName.replace(/\s*/g, '')
          this.address = this.addressNameStr + ' ' + this.memberInfo.address
        }
        this.memberStore = response.data.memberStore
        this.freight = response.data.postFee
        // 用来判断商品的配送方式
        return true
      }).catch(() => {
      })
    },
    ratioChange(e, item) {
      let price = ''
      if (/^(\d?)+(\.\d{0,2})?$/.test(e.mp.detail)) { // 正则验证，提现金额小数点后不能大于两位数字
        price = e.mp.detail
      } else {
        price = e.mp.detail.substring(0, e.mp.detail.length - 1)
      }
      if (price * 1 > item.sampleGoodsTotalRatio * 1) {
        this.$utils.showToast({title: '不能高于应获佣金比例数值！'})
        item.sampleAnchorRatio = item.sampleGoodsTotalRatio
      } else {
        item.sampleAnchorRatio = price
      }
      let myRatio = ''
      myRatio = parseFloat(item.sampleGoodsTotalRatio * 1 - item.sampleAnchorRatio * 1).toFixed(2)
      this.$delete(item, 'myRatio')
      this.$set(item, 'myRatio', myRatio)
    },
    sellerWordsChange(e, item) {
      this.$delete(item, 'sellerWords')
      this.$set(item, 'sellerWords', e.mp.detail)
    },
    submitPay() {
      if (this.notSupportNum) return
      this.$utils.showToast({
        title: '加载中',
        icon: 'loading'
      })
      if (!this.getShowBuyCard) {
        this.$utils.showToast({title: '已购买成功！'})
        setTimeout(() => {
          this.$pt.reLaunch({url: '/pages/home/main'})
        }, 1000)
        return
      }
      let that = this
      let rejectArr = []
      if (!this.messageIds.length) {
        this.submitOrder()
        return
      }
      this.$pt.requestSubscribeMessage({
        tmplIds: that.messageIds,
        success: function(res) {
          // 成功
          Object.keys(res).forEach(key => {
            if (res[key] === 'reject') {
              rejectArr.push(key)
            }
          })
          if (rejectArr.length) {
            that.messageIds = rejectArr
            that.$utils.showToast({title: '请允许消息通知！'})
          } else {
            that.submitOrder()
          }
        },
        fail(err) {
          // 失败
          that.$utils.showToast({title: '消息订阅失败，' + err.errCode})
          console.error(err)
          // 测试 支付功能 that.submitOrder()
          that.submitOrder()
        }
      })
    },
    submitOrder() {
      this.$pt.hideToast()
      this.$pt.removeStorageSync('pageBuyFrom')
      // console.log('submitOrder, shareMemberId: ' + this.shareMemberId)
      if (this.submitStatus) {
        return
      }
      this.submitStatus = true
      // 判断是否为快递配送方式下提交的订单
      // this.memberInfo.address = this.address
      if ((this.type === 3 && this.tabActive === '0') || this.type === 1) {
        if (!this.memberInfo.address && this.goodsType !== 20) {
          this.$utils.showToast({ title: '收货地址不能为空' })
          this.submitStatus = false
          return
        }
      }
      let goodsList = []
      // console.log(this.listData)
      this.listData.forEach((item) => {
        goodsList.push({
          cartId: item.cartId,
          skuId: item.skuId,
          goodsId: item.goodsId,
          goodsNum: item.goodsNum,
          goodsType: item.goodsType,
          sampleTotalRatio: item.sampleGoodsTotalRatio || '',
          sampleAnchorRatio: item.sampleAnchorRatio ? parseFloat(item.sampleAnchorRatio).toFixed(2) : '',
          sellerWords: item.sellerWords || ''
        })
      })
      let deliveryType = 0
      if ((this.type === 3 && this.tabActive === '0') || this.type === 1) {
        // 快递配送
        deliveryType = 1
      } else if ((this.type === 3 && this.tabActive === '1') || this.type === 2) {
        // 自提
        deliveryType = 2
      }
      // console.log('我在结算页面:', this.room_id)
      const params = {
        memberId: this.getMemberId,
        customerMemberId: this.getCustomerId,
        customerNickname: this.memberInfo.receiverName,
        customerPhone: this.memberInfo.receiverPhone,
        customerAddress: this.memberInfo.address,
        addressId: this.memberInfo.addressId,
        customerComment: this.comment,
        deliveryType: deliveryType,
        roleType: this.getRoleType ? this.getRoleType : '',
        goodsList: goodsList
      }
      if (!this.getShowBuyCard) {
        params.customerMemberId = this.getMemberId
      }
      if (this.shareMemberId && this.getCustomerId !== this.getMemberId) {
        params.shareMemberId = this.shareMemberId
      }
      if (this.$pt.getStorageSync('flowNo')) {
        params.flowNo = this.$pt.getStorageSync('flowNo')
      }
      // const aaa = true
      // if (aaa) return
      submitOrder(params).then((response) => {
        // console.log(response)
        if (response.isError) {
          this.submitStatus = false
          return
        }
        const that = this
        const payParams = response.data
        // 订单状态 -2: 已付款取消 -1: 未付款取消 0: 未付款, 1: 已付款 2: 已发货 3: 已收货 4: 已完成
        if (payParams.orderStatus === 1) {
          that.$pt.reLaunch({url: `/pages/shop/result/main?successFlag=1&price=${that.totalPrice}&orderId=${payParams.orderId}&resType=${payParams.orderGoodsDeliveryType}`})
          that.submitStatus = false
          return
        }
        if (this.total === 0) {
          that.$pt.reLaunch({url: `/pages/shop/result/main?successFlag=1&price=${that.totalPrice}&orderId=${payParams.orderId}&resType=${payParams.orderGoodsDeliveryType}`})
          return
        }
        that.$pt.requestPayment(
          {
            'timeStamp': payParams.timeStamp,
            'nonceStr': payParams.nonceStr,
            'package': payParams.package,
            'signType': payParams.signType,
            'paySign': payParams.paySign,
            'success': function(res) {
              that.$pt.reLaunch({url: `/pages/shop/result/main?successFlag=1&price=${that.totalPrice}&orderId=${payParams.orderId}&resType=${payParams.orderGoodsDeliveryType}`})
            },
            'fail': function(res) {
              that.$pt.reLaunch({url: `/pages/shop/result/main?successFlag=0&price=${that.totalPrice}&orderId=${payParams.orderId}&resType=${payParams.orderGoodsDeliveryType}`})
            }
          })
        that.submitStatus = false
      }).catch(() => {
      })
    }
  }
}
</script>

<style lang="less" scoped>
.container{
  padding: 10px;
  box-sizing: border-box;
  .sku-r-num{
    min-width: 48px;
  }
  .ratio-c{
    color: #2A68F5;
  }
  .ratio-bar{
    background: #f7f9fb;
    border-radius: 2px;
    .anchor-ratio-field{
      width: 63px;
      height: 20px;
      padding: 0 1px;
      box-sizing: border-box;
      border-radius: 3px;
      background: #e1e1e1;
      /deep/ .van-cell {
        margin: 0;
        border-top-left-radius: 3px;
        border-bottom-left-radius: 3px;
        border-top-right-radius: 0px;
        border-bottom-right-radius: 0px;
        padding: 0px 5px!important;
        height: 18px!important;
        min-height: 18px!important;
        line-height: 18px!important;
      }
      /deep/ .van-field__input{
        font-size: 11px!important;
        height: 18px!important;
        min-height: 18px!important;
        line-height: 18px!important;
      }
    }
    .per-tag{
      background: #e1e1e1;
      border-top-right-radius: 3px;
      border-bottom-right-radius: 3px;
    }
  }
  .comment-bar{
    background: #f7f9fb;
    border-radius: 2px;
    /deep/ .van-cell__title{
      max-width: 62px!important;
      min-width: 62px!important;
      font-size: 12px!important;
    }
    /deep/ .van-field__input{
      font-size: 12px!important;
    }
    /deep/ .van-cell {
      background: none;
      padding: 0px 7px;
    }
  }
  .head-box{
    padding: 19px 9px 19px 16.5px;
    background: #fff;
    border-radius: 4px;
    .head-content {
      .address-info {
        min-height: 40px;
      }
    }
  }
  .order-list-box {
    padding: 12px 16px 12px 16px;
    // justify-content: space-between;
    .order-text-info {
      flex: 1;
      justify-content: space-between;
      .norm {
        background: #F7F9FB;
        padding: 4px 8px;
        border-radius: 2px;
      }
      .hint-box {
        display: flex;
        justify-content: space-between;
        font-size: 12px;
        align-items: center;
        &>span:nth-child(1) {
          color:#f00
        }
        &>span:nth-child(2) {
          color: #fff;
          width: 30rpx;
          height: 30rpx;
          background: #aaa;
          border-radius: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
    .order-img {
      img {
        border-radius: 5px;
      }
    }
  }
  .memberinfo{
    min-height: 24px;
  }
  .label-ad-sp{
    display: inline-block;
    vertical-align: top;
  }
  .label-2{
    background: #FFEAEC;
    border-radius: 3px;
    color: #FF243D;
  }
  .label-3 {
    background: #FFEAEC;
    border-radius: 3px;
    color: #FF243D;
  }
  .label-1 {
    background: #E6F0FF;
    border-radius: 3px;
    color: #0066FF;
  }
  .label-4 {
    background: #EBEDFF;
    border-radius: 3px;
    color: #7427FF;
  }
  /deep/ .field-index--van-field {
    border-radius: 4px;
    .van-cell__title {
      font-size: 15px;
    }
  }
  .goods-other-info {
    border-radius: 4px;
    justify-content: space-between;
  }
  .bottom-area-box {
    padding: 5px 14px;
    border-radius: 24px;
    position: relative;
    .dis-active {
      background: #E5E5E5;
      color: #333;
    }
    .active {
      color: #fff;
      background: #7427FF;
    }
    .sure-btn{
      position: absolute;
      right: 0;
      top: 0;
      height: 100%;
      border-radius: 24px;
      width: 114px;
      border-left: 4rpx solid #f2f2f2;
      box-shadow: 12px 0px 0px 12px #F5F5F5;
    }
  }
    .remark-box{
    display: flex;
    justify-content: left;
    align-items: center;
    height: 50px;
    input{
      text-align: right;
    }
  }
    .box-layout{
    border-radius: 7px;
    background: white;
    margin-top: 13px;
    font-size: 15px;
    padding: 0 8px;
  }
}
.btn-position {
  position: fixed;
  bottom: 27.5px;
  width: 95%;
  z-index: 100;
}
</style>